package com.weipeep.sys.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.weipeep.api.entity.PageBean;
import com.weipeep.api.entity.ResultBean;
import com.weipeep.common.utils.Result;
import com.weipeep.common.utils.Util;
import com.weipeep.dubbo.request.UserInfoRequest;
import com.weipeep.dubbo.response.UserInfoResponse;
import com.weipeep.dubbo.service.TestService;
import com.weipeep.sys.domain.BannerDO;
import com.weipeep.sys.domain.MottoDO;
import com.weipeep.sys.domain.NavigateMenuDO;
import com.weipeep.sys.domain.NewsDO;
import com.weipeep.sys.service.BannerService;
import com.weipeep.sys.service.MottoService;
import com.weipeep.sys.service.NavigateMenuService;
import com.weipeep.sys.service.NewsService;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Controller;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api")
public class ApiController {

    @Autowired
    private MottoService mottoService;
    @Autowired
    private NewsService newsService;
    @Autowired
    private BannerService bannerService;
    @Autowired
    private NavigateMenuService navigateMenuService;

//    @Reference( version = "${hello.service.version}" )
    private TestService testService;

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    private String topic = "test-topic";
    @RequestMapping("/page_fetch_user")
    public  DeferredResult<ResultBean> apiFetchUser(int nextPage,int requestCount,int type){
        DeferredResult<ResultBean> deferredResult = new DeferredResult(1000l);
        // 查询列表数据
        deferredResult.onTimeout(new Runnable() {
            @Override
            public void run() {
                System.out.println("超时");
                ResultBean resultBean = new ResultBean();
                resultBean.setCode(300);
                resultBean.setMessage("超时");
                resultBean.setStatus(-1);
                deferredResult.setResult(resultBean);
            }
        });
        deferredResult.onCompletion(new Runnable() {
            @Override
            public void run() {
                System.out.println("完成");
            }
        });
        new Thread(new Runnable() {
            @Override
            public void run() {
                Page<MottoDO> page = new Page<>(nextPage, requestCount);
                MottoDO mottoDO = new MottoDO();
                mottoDO.setType(type);
                Wrapper<MottoDO> wrapper = new QueryWrapper<>(mottoDO);
                PageBean pageBean = new PageBean();
                page = (Page<MottoDO>) mottoService.page(page, wrapper);
                pageBean.setItems(page.getRecords());
                pageBean.setTotalResults(Integer.valueOf(page.getTotal()+""));
                pageBean.setNextPage(nextPage+1);
                pageBean.setPrevPage(nextPage-1);
                pageBean.setRequestCount(requestCount);
                pageBean.setResponseCount(page.getRecords().size());
                ResultBean resultBean = new ResultBean();
                resultBean.setCode(1);
                resultBean.setResult(pageBean);
                resultBean.setStatus(1);
                deferredResult.setResult(resultBean);
            }
        }).start();

        return deferredResult;
    }


    @RequestMapping("/ceshi/findById")
    @ResponseBody
    public UserInfoResponse testFindById(){
        UserInfoResponse userInfoResponse = testService.getUserByIdCard("1000938234");
        return userInfoResponse;
    }

    @RequestMapping("/ceshi/getUserByRequest")
    @ResponseBody
    public List<UserInfoResponse> testGetUserByRequest(){
        UserInfoRequest userInfoRequest = new UserInfoRequest();
        userInfoRequest.setIdCardList(Lists.newArrayList("aaa","bbb"));
        userInfoRequest.setUserName("wangyun");
        List<UserInfoResponse> userInfoResponseList = testService.getUserByRequest(userInfoRequest);
        return userInfoResponseList;
    }

    @RequestMapping("/ceshi/getUserByConditionList")
    @ResponseBody
    public List<UserInfoResponse> testGetUserByConditionList(){
        List<UserInfoResponse> userInfoResponseList = testService.getUserByConditionList(Lists.newArrayList("aa","bb"),19,"wangyun");
        return userInfoResponseList;
    }
    @RequestMapping("/ceshi/getUserByConditionSet")
    @ResponseBody
    public List<UserInfoResponse> testGetUserByConditionSet(){
        List<UserInfoResponse> userInfoResponseList = testService.getUserByConditionSet(Sets.newHashSet("aa","bb"),19,"wangyun");
        return userInfoResponseList;
    }

    @RequestMapping(value = "/news",method = RequestMethod.GET)
    @ResponseBody
    public ResultBean<IPage> news(Integer page, Integer size){
        ResultBean result = new ResultBean();
        IPage<NewsDO> iPage = new Page<>(page,size);
        iPage = newsService.page(iPage);
        result.setResult(iPage);
        return result;
    }

    @RequestMapping("/login")
    @ResponseBody
    public ResultBean apiLogin(String account,String pwd){
        // 查询列表数据
        ResultBean resultBean = new ResultBean();
        if(account.equals("abcd")&&pwd.equals("123456")){
            resultBean.setMessage("登录成功！");
            resultBean.setStatus(1);
        }
        else
        {
            resultBean.setMessage("账号或密码错误！");
            resultBean.setStatus(0);
        }
        return resultBean;
    }
    @RequestMapping("/banner")
    @ResponseBody
    public ResultBean bannerList(){
        // 查询列表数据
        ResultBean resultBean = new ResultBean();
        List<BannerDO> bannerDOList = bannerService.list();
        resultBean.setResult(bannerDOList);
        return resultBean;
    }
    @RequestMapping("/navigate/menus")
    @ResponseBody
    public ResultBean navigateMenus(){
        // 查询列表数据
        ResultBean resultBean = new ResultBean();
        QueryWrapper<NavigateMenuDO> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted",0).orderByAsc("menu_order");
        List<NavigateMenuDO> navigateMenuDOList = navigateMenuService.list(wrapper);
        resultBean.setResult(navigateMenuDOList);
        return resultBean;
    }

    @GetMapping("/send")
    public String send(String params,Integer count) {
        System.out.println("[ 收到请求 ]");
        int total = 100000;
        if (count!=null){
            total = count.intValue();
        }
        if (params==null){
            params = "";
        }
        for (int index=1;index<total;index++){
            String msg=null;
            msg = params+"参数_"+index;
            ListenableFuture<SendResult<String,String>> future =  kafkaTemplate.send(topic, msg);
            logger.info("发送消息:{}",msg);
        }
        System.out.println("[ 返回响应 ]");
        return "您的任务已提交";
    }
}
